/**
 * A = sum (ai!)
 * => N <= 8
 */

/**
 * @author TrinhNX
 * @start_date	: 2015/04/24
 * @end_date 	:
 */
public class Euler034 {
	public static void main(String[] args) {
		final long start = System.currentTimeMillis();
		// Optimize 1; MAX is 1999999, not 2903040
		final int MAX = 1999999; // 1999999
		final int[] DATA= { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
		int value = 100; // Start with 100 not 10
		int temp_sum, m, n;
		boolean need_check;
		while (value++ < MAX) {
			temp_sum = 0;
			n = value;
			need_check = true;
			do {
				m = n % 10;
				if (value > DATA[m]) {
					 temp_sum += DATA[m];
					n = n / 10;
				} else {
					need_check = false;
					value += (10 - m);
					break;
				}
			} while (n > 0);
			if (need_check) {
				if (value == temp_sum)
					System.out.println(value);
			}
		}

		System.out.println("End after: " + (System.currentTimeMillis() - start));
	}

}
